#coding=utf-8
import SimpleHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import SocketServer
import os,io,shutil
import logging
import cgi,sqlite3
import urlparse,json
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

conn = sqlite3.connect('./database/data.sqlite')
#cursor = conn.cursor()
print "Opened database successfully";
# 增数据 ## 可以做多次execute后commit
# cursor.execute("INSERT INTO dept (name, type) VALUES ('人事处', 2)");
# cursor.execute("INSERT INTO dept (name, type) VALUES ('人事处', 3)");
# cursor.execute("INSERT INTO dept (name, type) VALUES ('人事处', 4)");
# conn.commit()
# print "Records created successfully";

# 删数据
# cursor.execute("DELETE from dept where id=2;")
# conn.commit()
# print "DELETE done successfully";

# 改数据
# cursor.execute("UPDATE dept SET type=8 WHERE id=3")
# conn.commit()
# print "Update OK .  Total number of rows updated :", conn.total_changes

# 查数据
# cursor2 = cursor.execute("SELECT *  from dept")
# for row in cursor2:
#    print "id = ", row[0]
#    print "name = ", row[1]
#    print "type = ", row[2], "\n"
# print "SELECT done.  Operation done successfully";

log_path = './logs/run_server_logs.log'
logging.basicConfig(level=logging.INFO,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S',filename=log_path)

# 查询结果转换为字典组
def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

class MyHttpHandler(SimpleHTTPRequestHandler):
    
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
    
    def send_datas(self,contents):
        #指定返回编码
        enc = "UTF-8"
        #contents = contents.encode(enc)          
        f = io.BytesIO()
        f.write(contents)
        f.seek(0)  
        self.send_response(200)  
        self.send_header("Content-type", "text/html; charset=%s" % enc)  
        self.send_header("Content-Length", str(len(contents)))  
        self.end_headers() 
        shutil.copyfileobj(f,self.wfile)
 
    def do_GET(self):
        logging.info("got get request "+str(self.path))
        path = str(self.path)
        #self.send_datas('get请求方式'+path)
        if path=='/getData/' :
            flag = 1
            results = {"status":flag,"msg":"msg abcd很好"}
            self.send_datas(json.dumps(results, ensure_ascii=False))
        else:
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
              
    def do_POST(self):
        logging.info("got post!!")
        datasets = cgi.FieldStorage(fp = self.rfile,headers = self.headers,environ = {'REQUEST_METHOD': 'POST'})
        logging.info(str(datasets))
        path = self.path

        # 获取tables初始化需要的数据，一次性打包返回
        if path=='/tables/getInitDatas/': 
            conn.row_factory = dict_factory
            cursor = conn.cursor()
            retData = {}
            # 部门
            depts = cursor.execute("SELECT    id,name,type,is_link_stud,is_link_jxdwjs,is_link_znbmgzry      from dept")
            retData['depts'] = cursor.fetchall()
            # 所有被评价人
            beipingrens = cursor.execute("SELECT   id,name,dept_id,level     from beipingren")
            retData['beipingrens'] = cursor.fetchall()

            self.send_datas(json.dumps(retData))
        
        # 获取tables被评人信息
        elif path=="/tables/getBeipingrens/":
            dept_id = datasets.getvalue('dept_id')
            level   = datasets.getvalue('level')
            conn.row_factory = dict_factory
            cursor = conn.cursor()
            retData = {}
            retData["form"]={"dept_id":dept_id,"level":level}
            sql = ""
            if dept_id == "_" and level != "_": # 按部门查找
                sql = "SELECT id,name,dept_id,level FROM beipingren WHERE level=%s" % (level)
            elif dept_id != "_" and level == "_":  # 按级别查找
                sql = "SELECT id,name,dept_id,level FROM beipingren WHERE dept_id=%s" % (dept_id)
            elif dept_id != "_" and level != "_":  # 按部门、级别查找
                sql = "SELECT id,name,dept_id,level FROM beipingren WHERE dept_id=%s AND level=%s" % (dept_id,level)
            else:  # 找出所有被评价人
                sql = "SELECT id,name,dept_id,level FROM beipingren"
            
            rs = cursor.execute(sql)
            retData['beipingrens'] = cursor.fetchall()
            retData['sql'] = sql
            self.send_datas(json.dumps(retData))

        else :
            id = datasets.getvalue('id')
            name = datasets.getvalue('name')
            
            msg = " action==" +self.path+  "  name=="+str(name)+"   id=="+str(id)
            flag = 1
            results = {"status":flag,"msg":msg}
            #self.send_datas(str(results))
            #bJson = json.dumps(bItem, ensure_ascii=False)
            self.send_datas(json.dumps(results))
        
        
def start_server():
    server_host = '127.0.0.1'
    server_port = 8090
    httpd = SocketServer.TCPServer((server_host,server_port), MyHttpHandler)
    logging.info('\nStart server success ... \nserver_host:'+server_host+'   server_port:'+str(server_port))
    print('exe_server started on '+str(server_host)+' server_port:'+str(server_port))
    httpd.serve_forever()

if __name__ == "__main__":
    start_server()

